package ld;

import ld.utils.JsonOut;
import ld.utils.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "UserInfoServlet")
public class UserInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String email = session.getAttribute("login_user_email").toString();

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        if (email == null || email.isEmpty()){
            out.println(JsonOut.error(201, "not_login"));
            return;
        }

        ResultSet userSet = MysqlUtils.getUserInfo(email);
        if (userSet == null){
            out.println(JsonOut.error(101, "not_exist"));
            return;
        }

        Map<String, Object> userInfoJObject = new HashMap<>();
        try {
            String username = userSet.getString(1);
            String emailActive = userSet.getString(2);
            String area = userSet.getString(3);
            String sex = userSet.getString(4);
            userInfoJObject.put("username", username != null ? username : "");
            userInfoJObject.put("email_active", emailActive != null ? emailActive : "");
            userInfoJObject.put("area", area != null ? area : "");
            userInfoJObject.put("sex", sex != null ? sex : "");

            System.out.println(userInfoJObject);

            out.println(JsonOut.common(200, "user info", userInfoJObject));


        }catch (Exception e){
            e.printStackTrace();
            out.println(JsonOut.error(500, "error"));
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        PrintWriter out = response.getWriter();
//        out.println(JsonOut.error(403, "forbidden"));
        doPost(request, response);
    }
}
